package com.lyl.auth;

import javax.annotation.Resource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Order(10)
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Resource
	private CustomUserDetailsService customUserDetailsService;

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
	}

	// 把 AuthenticationManager 配置到 Spring 容器中，配置Oauth2 的时候会用到
	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
	/*	http.csrf().disable();
		http.requestMatchers().antMatchers("/oauth/**")
		.and()
		.authorizeRequests().antMatchers("/oauth/**").authenticated();*/

/*
		http.formLogin()
				.loginPage("/login").permitAll()
				.and()
				.authorizeRequests()
				.antMatchers("/login").permitAll()
				//这个地址由AuthorizationServer使用，不需要登录拦截
				.antMatchers("/oauth/**").permitAll()
				.anyRequest().authenticated();//其他任意请求需要登录*/

		http.csrf().disable()
				.authorizeRequests()
				.antMatchers("/","/oauth/**","/login").permitAll()
				.anyRequest().authenticated()
				.and()
				.formLogin()
				.loginPage("/login")
				.permitAll();

	}


	// 把 PasswordEncoder 放到 Spring 容器中
	// Springboot2 貌似必须把这个配置到 Spring 容器中，不然会报错
	@Bean
	PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

}
